package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("SiteService")
@Transactional

public class SiteServiceImpl extends CmiEmaService implements SiteService {
	public SiteServiceImpl() {
	}

	@Transactional
	public Site saveSite(Site site) {
		Set<Rule> existingRulesForSite = new HashSet<Rule>();
		Set<Url> existingUrlsForSite = new HashSet<Url>();

		Set<Rule> selectedRulesForSite = site.getRulesForSite();
		Set<Url> selectedUrlsForSite = site.getUrlsForSite();

		if (site.getId() == null) {

			Site existingSite = siteDAO.findSiteByPhysicalPrimaryKey(site.getName(), site.getDomain());

			if (isEquals(site, existingSite)) {
				return existingSite;
			}

			site = siteDAO.store(site);
			siteDAO.flush();

			for (Rule relatedRule : selectedRulesForSite) {
				relatedRule.setSite(site);
				ruleDAO.store(relatedRule);
			}
			for (Url relatedUrl : selectedUrlsForSite) {
				relatedUrl.setSite(site);
				urlDAO.store(relatedUrl);
			}
		} else {
			Site existingSite = siteDAO.findSiteByPrimaryKey(site.getId());

			existingRulesForSite = existingSite.getRulesForSite();
			existingUrlsForSite = existingSite.getUrlsForSite();

			Set<Rule> prepareDeleteRulesForSite = new HashSet<Rule>();
			Set<Rule> prepareAddRulesForSite = new HashSet<Rule>();

			prepareDeleteRulesForSite.addAll(selectedRulesForSite);
			prepareDeleteRulesForSite.addAll(existingRulesForSite);

			prepareAddRulesForSite.addAll(selectedRulesForSite);
			prepareAddRulesForSite.addAll(existingRulesForSite);

			prepareDeleteRulesForSite.removeAll(selectedRulesForSite);
			prepareAddRulesForSite.removeAll(existingRulesForSite);

			for (Rule relatedRule : prepareAddRulesForSite) {
				relatedRule.setSite(site);
				ruleDAO.store(relatedRule);
			}

			for (Rule relatedRule : prepareDeleteRulesForSite) {
				relatedRule.setSite(null);
				ruleDAO.store(relatedRule);
			}
			Set<Url> prepareDeleteUrlsForSite = new HashSet<Url>();
			Set<Url> prepareAddUrlsForSite = new HashSet<Url>();

			prepareDeleteUrlsForSite.addAll(selectedUrlsForSite);
			prepareDeleteUrlsForSite.addAll(existingUrlsForSite);

			prepareAddUrlsForSite.addAll(selectedUrlsForSite);
			prepareAddUrlsForSite.addAll(existingUrlsForSite);

			prepareDeleteUrlsForSite.removeAll(selectedUrlsForSite);
			prepareAddUrlsForSite.removeAll(existingUrlsForSite);

			for (Url relatedUrl : prepareAddUrlsForSite) {
				relatedUrl.setSite(site);
				urlDAO.store(relatedUrl);
			}

			for (Url relatedUrl : prepareDeleteUrlsForSite) {
				relatedUrl.setSite(null);
				urlDAO.store(relatedUrl);
			}
			site = siteDAO.store(site);
			siteDAO.flush();
		}

		ruleDAO.flush();
		urlDAO.flush();
		return site;
	}

	public void deleteSite(Site site) {
		siteDAO.remove(site);
		siteDAO.flush();
	}

	@Transactional
	public void deleteSites(Set<Integer> deleteSitesId) {
		Query query = siteDAO.createNamedQuery("deleteSitesById", -1, -1);
		query.setParameter(1, deleteSitesId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Site> loadSites() {
		return siteDAO.findAllSites();

	}

	@Transactional
	public Set<Site> loadReferenceSites(Set<Site> sites) {
		Iterator<Site> sitesIterator = sites.iterator();
		Set<Site> referencedSites = new HashSet<>();
		while (sitesIterator.hasNext()) {
			Site currentSite = sitesIterator.next();

			if (!currentSite.getRulesForSite().isEmpty()) {
				referencedSites.add(currentSite);
				continue;
			}

			if (!currentSite.getUrlsForSite().isEmpty()) {
				referencedSites.add(currentSite);
				continue;
			}
		}
		return referencedSites;
	}

	public Set<Site> loadSitesByIdSet(Set<Integer> siteIdSet) {

		Iterator<Integer> siteIdIterator = siteIdSet.iterator();
		Set<Site> siteSet = new HashSet<>();
		while (siteIdIterator.hasNext()) {
			Integer id = siteIdIterator.next();
			Site currentSite = siteDAO.findSiteById(id);
			siteSet.add(currentSite);
		}
		return siteSet;
	}

	@Transactional
	public List<Site> findAllSites(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Site>(siteDAO.findAllSites(startResult, maxRows));
	}

	@Transactional
	public Site findSiteByPrimaryKey(Integer id) {
		return siteDAO.findSiteByPrimaryKey(id);
	}

	@Transactional
	public Integer countSites() {
		return ((Long) siteDAO.createQuerySingleResult("select count(o) from Site o").getSingleResult()).intValue();
	}

	@Transactional
	public Integer countSites(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Site.class);
		return ((Long) siteDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countSitesByName(String queryName) {
		Query query = siteDAO.createNamedQuery("countSitesByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countSitesByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Site.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadSiteObjectReferencedSet(Site site) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();

		Set<Integer> rulesIds = new HashSet<Integer>();
		for (Rule obj : site.getRulesForSite()) {

			rulesIds.add(obj.getId());
		}
		objectReferencedSetMap.put("rulesIds", rulesIds);
		Set<Integer> urlsIds = new HashSet<Integer>();
		for (Url obj : site.getUrlsForSite()) {

			urlsIds.add(obj.getId());
		}
		objectReferencedSetMap.put("urlsIds", urlsIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadSiteClassReferencedSet(Site site) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("rules", ruleDAO.findAllRules());
		classReferencedSetMap.put("urls", urlDAO.findAllUrls());

		return classReferencedSetMap;
	}

	public boolean isEquals(Site site, Object obj) {
		if (obj == site)
			return true;
		if (!(obj instanceof Site))
			return false;
		Site comparedSite = (Site) obj;
		if (!CheckPropertyEqual(site.getName(), comparedSite.getName())) {
			return false;
		}
		if (!CheckPropertyEqual(site.getDomain(), comparedSite.getDomain())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

